var mysql = require('mysql');
var $dbConfig = require('../conf/database');
var rMsg = require('./ResultMessage');
// 使用连接池，避免开太多的线程，提升性能
var pool = mysql.createPool($dbConfig.mysql);
/**
 * 对query执行的结果自定义返回JSON结果
 */
function responseDoReturn(res, result, resultJSON) {
    if (typeof result === 'undefined') {
        res.json({
            code: '201',
            msg: 'failed to do'
        });
    } else {
        res.json(result);
    }
};

/**
 * 封装query之sql带不占位符func
 */
function query(sql) {
    return new Promise(function (resolve, reject) {
        pool.getConnection(function (err, connection) {
            connection.query(sql, function (err, rows) {
                //释放链接  
                connection.release();
                if (err) reject(new rMsg(err.message, "", 500))
                return resolve(new rMsg(rows))
            });
        });
    });
}

/**
 * 封装query之sql带占位符func
 * @param {*} sql 添加 sql ex:INSERT INTO websites(Id,name,url,alexa,country) VALUES(0,?,?,?,?)';
 * @param {*} args 添加参数    ex:['菜鸟工具', 'https://c.runoob.com', '23453', 'CN'];
 */
function queryArgs(sql, args) {
    return new Promise(function (resolve, reject) {
        pool.getConnection(function (err, connection) {
            connection.query(sql, args, function (err, rows) {
                //释放链接
                connection.release();
                if (err) reject(new rMsg(err.message, "", 500))
                return resolve(new rMsg(rows))
            });
        });
    });
}

//exports
module.exports = {
    query: query,
    queryArgs: queryArgs,
    doReturn: responseDoReturn
}